import { prisma } from "../prisma/client";
import { PaginationUtil } from "../utils/pagination.util";
// 获取所有角色
export const getAllRoles = async (
  page: number = 1,
  pageSize: number = 10,
  options: object = {}
) => {
  return PaginationUtil.paginate(prisma.role, options, page, pageSize);
};

// 根据ID获取角色
export const getRoleById = async (id: number) => {
  return await prisma.role.findUnique({
    where: { id },
    include: {
      users: true,
    },
  });
};

// 创建角色
export const createRole = async (data: { name: string }) => {
  return await prisma.role.create({
    data,
  });
};

// 更新角色
export const updateRole = async (
  id: number,
  data: {
    name?: string;
  }
) => {
  return await prisma.role.update({
    where: { id },
    data,
  });
};

// 删除角色
export const deleteRole = async (id: number) => {
  return await prisma.role.delete({
    where: { id },
  });
};

// 授予权限
export const assignPermissionsToRole = async (
  roleId: number,
  permissionIds: number[]
) => {
  // 删除旧权限
  await prisma.rolePermission.deleteMany({
    where: { roleId },
  });
  // 批量创建权限关联
  const newRolePermissions = permissionIds.map((permissionId) => ({
    roleId,
    permissionId,
  }));
  await prisma.rolePermission.createMany({
    data: newRolePermissions,
  });
  // 返回带权限的角色信息
  return prisma.role.findUnique({
    where: { id: roleId },
    include: {
      rolePermissions: {
        include: {
          permission: true,
        },
      },
    },
  });
};
